package com.znufe.exam.controller.admin;

import java.util.Date;
import java.util.List;

import com.github.pagehelper.PageInfo;
import com.znufe.exam.base.BaseApiController;
import com.znufe.exam.configuration.config.annotation.Log;
import com.znufe.exam.configuration.config.enums.BusinessType;
import com.znufe.exam.configuration.config.model.LoginUser;
import com.znufe.exam.configuration.config.service.TokenService;
import com.znufe.exam.configuration.config.utils.ServletUtils;
import com.znufe.exam.domain.User;
import com.znufe.exam.domain.classes.StudentClassResponseObject;
import com.znufe.exam.utility.DateTimeUtil;
import com.znufe.exam.utility.PageInfoHelper;
import com.znufe.exam.viewmodel.admin.classes.StudentClassCreateVM;
import com.znufe.exam.viewmodel.admin.classes.StudentClassPageRequestVM;
import com.znufe.exam.viewmodel.admin.classes.StudentClassResponseVM;
import com.znufe.exam.viewmodel.admin.student.StudentResponseVM;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import com.znufe.exam.domain.StudentClass;
import com.znufe.exam.service.StudentClassService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

import com.znufe.exam.base.RestResponse;
import com.znufe.exam.base.SystemCode;

import javax.validation.Valid;

/**   
 * 
 * @Description:  班级信息表接口层
 * @Author:       lin keqing   
 * @CreateDate:   StudentClass
 * @Version:      V1.0
 *    
 */
@Api(description = "班级信息表",value="班级信息表" )
@RestController("AdminStudentClassController")
@RequestMapping(value="api/admin/student_class")
public class StudentClassController extends BaseApiController {

	Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	public StudentClassService studentClassService;

    @Autowired
    private TokenService tokenService;
	
    public StudentClassController(StudentClassService studentClassService) {
    	this.studentClassService = studentClassService;
	}

    @PreAuthorize("@ss.hasAnyPermi('class:classmate:add,class:classmate:update')")
    @Log(title = "班级管理", businessType = BusinessType.EDIT)
	@RequestMapping(value="/edit", method = RequestMethod.POST)
	@ApiOperation(value = "班级信息的编辑接口（新增/更新）",
			      notes = "新增/更新某个班级的信息[student_class](更新请传入班级id)，作者：lin keqing")
	public RestResponse<StudentClass> edit(@RequestBody @Valid StudentClassCreateVM model) {
		if (model.getId() == null) {
			// 若请求体中没有id，判断新增班级名称是否已经存在
			StudentClass existStudentClass = studentClassService
					.selectByClassName(model.getClassName());

			if (null != existStudentClass) {
				return new RestResponse<>(2, "班级已存在");
			}
		}

		//当前用户
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        User user = loginUser.getUser();
		StudentClass studentClass = studentClassService
				.saveStudentClassFromVM(model, user);
    	return RestResponse.ok(studentClass);
	}

    @PreAuthorize("@ss.hasPermi('class:classmate:delete')")
    @Log(title = "班级管理", businessType = BusinessType.DELETE)
	@RequestMapping(value="/delete/{id}", method = RequestMethod.POST)
	@ApiOperation(value = "班级信息的删除接口（通过班级id号删除）", notes = "删除班级信息[student_class]，作者：lin keqing")
	public RestResponse delete(@PathVariable Integer id) {
		StudentClass studentClass = studentClassService.selectByPrimaryKey(id);
		studentClass.setIsDeleted(1);
		studentClassService.updateByIdFilter(studentClass);
		return RestResponse.ok();
	}

    @PreAuthorize("@ss.hasPermi('class:classmate:update')")
    @Log(title = "班级管理", businessType = BusinessType.UPDATE)
	@RequestMapping(value="/changeStatus/{id}", method = RequestMethod.POST)
	@ApiOperation(value = "某个班级的启用状态改变接口（禁用/启用）",
			      notes = "改变某个班级的启用状态[student_class]，作者：lin keqing")
	public RestResponse<Integer> changeStatus(@PathVariable Integer id) {
    	StudentClass studentClass = studentClassService.selectByPrimaryKey(id);
    	Integer newStatus = studentClass.getIsEnabled() == 1 ? 0 : 1;
    	studentClass.setIsEnabled(newStatus);
    	studentClass.setModifiedTime(new Date());
    	studentClassService.updateByIdFilter(studentClass);
    	return RestResponse.ok(newStatus);
	}

    @PreAuthorize("@ss.hasPermi('class:classmate:list')")
    @RequestMapping(value = "/page", method = RequestMethod.POST)
	@ApiOperation(value = "学生班级表的页面查询接口（无参数查找/按班级名称查找）",
				  notes = "查询班级信息[student_class]，作者：lin keqing")
    public RestResponse<PageInfo<StudentClassResponseVM>> pageList(@RequestBody StudentClassPageRequestVM model) {
        model = StudentClassPageRequestVM.wipeBlank(model);
    	PageInfo<StudentClassResponseObject> pageInfo = studentClassService.studentClassPage(model);
        PageInfo<StudentClassResponseVM> page = PageInfoHelper.copyMap(pageInfo,
                d -> {
					StudentClassResponseVM vm = StudentClassResponseVM.from(d);
					//Integer stuCount = studentClassService.selectClassStuCountById(vm.getId());
					//vm.setStuCount(stuCount);
					return vm;
				});
		return RestResponse.ok(page);

    }

    @PreAuthorize("@ss.hasPermi('class:classmate:query')")
	@RequestMapping(value = "/select/{id}", method = RequestMethod.POST, produces = "application/json")
	@ApiOperation(value = "根据id查找班级(编辑按钮调用这个接口)",notes = "返回部分班级信息")
	@ApiImplicitParam(paramType="path", name = "id", value = "班级id", dataType = "int",required = true)
	public RestResponse<StudentClassResponseVM> select(@PathVariable Integer id) {
		StudentClass studentClass = studentClassService.selectByPrimaryKey(id);
		StudentClassResponseVM vm = modelMapper.map(studentClass, StudentClassResponseVM.class);
		vm.setCreateTime(DateTimeUtil.dateFormat(studentClass.getCreateTime()));
		return RestResponse.ok(vm);
	}

	/**
	 * @explain 查询班级信息表对象  <swagger GET请求>
	 * @param   id
	 * @return  studentClass
	 * @author  lin keqing
	 * @time    StudentClass
	 */
	/*
	@GetMapping("/getStudentClassById/{id}")
	@ApiOperation(value = "获取班级信息表信息", notes = "获取班级信息表信息[studentClass]，作者：lin keqing")
	@ApiImplicitParam(paramType="path", name = "id", value = "班级信息表id", required = true, dataType = "Integer")
	public RestResponse<StudentClass> getStudentClassById(@PathVariable("id")Integer id) {

		try {
			StudentClass studentClass=studentClassService.selectByPrimaryKey(id);
			if (studentClass!=null) {
				return RestResponse.ok(studentClass);
			} else {
				logger.error("查询班级信息表执行失败："+studentClass.toString());
				return RestResponse.fail(SystemCode.NoDataExist.getCode(),SystemCode.NoDataExist.getMessage());
			}
		} catch (Exception e) {
			logger.error("查询班级信息表执行异常："+e.getMessage());
			return RestResponse.fail(SystemCode.InnerError.getCode(),SystemCode.InnerError.getMessage());
		}
	}
	*/

	/**
	 * @explain 添加班级信息表对象
	 * @param   studentClass
	 * @return  int
	 * @author  lin keqing
	 * @time    StudentClass
	 */
	/*
	@PostMapping("/insertSelective")
	@ApiOperation(value = "添加班级信息表", notes = "添加班级信息表[studentClass],作者：lin keqing")
	public RestResponse<Integer> insertSelective(StudentClass studentClass) {
		try {
			int rg=studentClassService.insertSelective(studentClass);
			if (rg > 0) {
				return RestResponse.ok(rg);
			} else {
				logger.error("添加班级信息表执行失败："+studentClass.toString());
				return RestResponse.fail(SystemCode.InsertDataFail.getCode(),SystemCode.InsertDataFail.getMessage());
			}
		} catch (Exception e) {
			logger.error("添加班级信息表执行异常："+e.getMessage());
			return RestResponse.fail(SystemCode.InnerError.getCode(),SystemCode.InnerError.getMessage());
		}
	}
	*/

	/**
	 * @explain 删除班级信息表对象
	 * @param   id
	 * @return  int
	 * @author  lin keqing
	 * @time    StudentClass
	 */
	/*
	@PostMapping("/deleteByPrimaryKey")
	@ApiOperation(value = "删除班级信息表", notes = "删除班级信息表,作者：lin keqing")
	@ApiImplicitParam(paramType="query", name = "id", value = "班级信息表id", required = true, dataType = "Integer")
	public RestResponse<Integer> deleteByPrimaryKey(Integer id) {
		try {
			int reg=studentClassService.deleteByPrimaryKey(id);
			if (reg > 0) {
				return RestResponse.ok(reg);
			} else {
				logger.error("删除班级信息表失败ID："+id);
				return RestResponse.fail(SystemCode.DeleteDataFail.getCode(),SystemCode.DeleteDataFail.getMessage());
			}
		} catch (Exception e) {
			logger.error("删除班级信息表执行异常："+e.getMessage());
			return RestResponse.fail(SystemCode.InnerError.getCode(),SystemCode.InnerError.getMessage());
		}
	}
	*/

	/**
	 * @explain 修改班级信息表对象
	 * @param   studentClass
	 * @return  studentClass
	 * @author  lin keqing
	 * @time    StudentClass
	 */
	/*
	@ApiOperation(value = "修改班级信息表", notes = "修改班级信息表[studentClass],作者：lin keqing")
	@PostMapping("/updateByPrimaryKeySelective")
	public RestResponse<Integer> updateByPrimaryKeySelective(StudentClass studentClass) {
		try {
			int reg = studentClassService.updateByPrimaryKeySelective(studentClass);
			if (reg > 0) {
				return RestResponse.ok(reg);
			} else {
				logger.error("修改班级信息表失败ID："+studentClass.toString());
				return RestResponse.fail(SystemCode.UpdateDataFail.getCode(),SystemCode.UpdateDataFail.getMessage());
			}
		} catch (Exception e) {
			logger.error("修改班级信息表执行异常："+e.getMessage());
			return RestResponse.fail(SystemCode.InnerError.getCode(),SystemCode.InnerError.getMessage());
		}
	}
	*/

	/**
	 * @explain 获取匹配班级信息表
	 * @param   studentClass
	 * @return  List<StudentClass>
	 * @author  lin keqing
	 * @time    StudentClass
	 */
	/*
	@ApiOperation(value = "条件查询班级信息表", notes = "条件查询[studentClass],作者：lin keqing")
	@PostMapping("/queryStudentClassList")
	public RestResponse<List<StudentClass>> queryStudentClassList(StudentClass studentClass) {
		try {
			List<StudentClass> list = studentClassService.queryStudentClassList(studentClass);
			return RestResponse.ok(list);
		} catch (Exception e) {
			logger.error("获取班级信息表执行异常："+e.getMessage());
			return RestResponse.fail(SystemCode.InnerError.getCode(),SystemCode.InnerError.getMessage());
		}
	}
    */
}